<list_name>=[[value1,...],[value1,...],valueN] OR <list_name 1>=[value1,value2,valueN] <list_name 2>=[value1,value2,valueN] <list_name 1>=[list_name 1,list_name 2]
a=[1,3,5] b=[2,7,6,9] c=[a,b] print(c) c=[[1,3,5],[2,7,6,9]] print(c)
[[1, 3, 5], [2, 7, 6, 9]] [[1, 3, 5], [2, 7, 6, 9]]
nlst=[[1, 3, 5], [2, 7, 6, 9]] s=0 for lst in nlst: for n in lst: s=s+n print("Sum is ",s)
nlst=[[1, 3, 5], [2, 7, 6, 9]] for lst in nlst: s=0 for n in lst: s=s+n print("Sum is ",s)
Sum is 9 Sum is 24
slst=[["jan-2017","Amit",45000], ["jan-2017","Gopal",15000], ["feb-2017","Amit",25000]] s=0 for lst in slst: s=s+ lst[2] print("Total sales is ",s)
Total sales is 85000
lst=['ram','ganpat','shyam','gopal','raj','mona'] lst.sort() print(lst) lst.sort(reverse=True) print(lst) lst.sort(key=len) print(lst)
['ganpat', 'gopal', 'mona', 'raj', 'ram', 'shyam'] ['shyam', 'ram', 'raj', 'mona', 'gopal', 'ganpat'] ['ram', 'raj', 'mona', 'shyam', 'gopal', 'ganpat']
lst=['ram','ganpat','shyam','gopal','raj','mona'] lst.sort() print(lst) def cmp(val): return val[1:] lst.sort(key=cmp) print(lst)
['ganpat', 'gopal', 'mona', 'raj', 'ram', 'shyam'] ['raj', 'ram', 'ganpat', 'shyam', 'mona', 'gopal']
lst=["Gopal Jain","Amit R. Pandey","Mohan Mantri","Raj M. Joshi","Madan Agrawal"] lst.sort() print(lst) def cmp(val): arr=val.split() return arr[-1] lst.sort(key=cmp) print(lst)
['Amit R. Pandey', 'Gopal Jain', 'Madan Agrawal', 'Mohan Mantri', 'Raj M. Joshi'] ['Madan Agrawal', 'Gopal Jain', 'Raj M. Joshi', 'Mohan Mantri', 'Amit R. Pandey']
lst=[1201,61,234,10002,55] lst.sort() print(lst) def cmp(val): s=0 while val>0 : d=val%10 s=s+d val=val//10 return s lst.sort(key=cmp) print(lst)
[55, 61, 234, 1201, 10002] [10002, 1201, 61, 234, 55]
lst=["seeta pandey","amit joshi","gopal pandey","raj joshi","chetan joshi"] def cmp(val): arr=val.split() return arr[1]+arr[0] lst.sort(key=cmp) print(lst)
['amit joshi', 'chetan joshi', 'raj joshi', 'gopal pandey', 'seeta pandey']
lst=["seeta","amit","gopal","RAJ","chetan"] lst.sort() print(lst) def cmp(val): return val.upper() lst.sort(key=cmp) print(lst)
['RAJ', 'amit', 'chetan', 'gopal', 'seeta'] ['amit', 'chetan', 'gopal', 'RAJ', 'seeta']
class Person: def __init__(self,nm,ct): self.name=nm self.city=ct def showdata(self): print(self.name,self.city) def cmp(p): return p.city a=Person("Amit","Mumbai") b=Person("Gopal","Amravati") c=Person("Raj","Akola") d=Person("Mona","Nagpur") e=Person("Raja","Chandrapur") lst=[a,b,c,d,e] lst.sort(key=cmp) for obj in lst: obj.showdata()
Raj Akola Gopal Amravati Raja Chandrapur Amit Mumbai Mona Nagpur